package com.madoka.base.utils.validation.validators;

import com.madoka.base.utils.validation.constraints.DateRange;
import org.apache.commons.beanutils.PropertyUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Date;

/**
 * @author Chen Yan Yi
 */
public class DateRangeValidator implements ConstraintValidator<DateRange, Object> {

    private String begin;
    private String end;
    private Boolean current;

    @Override
    public void initialize(final DateRange constraintAnnotation) {
        begin = constraintAnnotation.begin();
        end = constraintAnnotation.end();
        current = constraintAnnotation.current();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            final Object beginObj = PropertyUtils.getProperty(value, begin);
            final Object endObj = PropertyUtils.getProperty(value, end);

            Date beginDate = (Date) beginObj;
            Date endDate = (Date) endObj;
            Date currentDate = new Date();

            return current ? (!currentDate.after(endDate) && !currentDate.before(beginDate)) : (!beginDate.after
                    (endDate));

        } catch (final Exception ignore) {
            // ignore
        }
        return true;
    }

}
